﻿using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;

namespace AzureLogManager.Log
{
    public static class LogManager
    {
        #region - Properties -

        public static CloudTable Table { get; set; }

        private static String _logType;
        public static String LogType
        {
            get { return LogManager._logType; }
            set
            {
                LogManager._logType = value;

                if (LogManager._logType.Equals("verbose", StringComparison.OrdinalIgnoreCase))
                {
                    LogManager._isVerbose = true;
                }
                else
                {
                    LogManager._isVerbose = false;
                }
            }
        }

        private static Boolean _isVerbose;

        #endregion

        public static void Log(String type, Int64 duration, [CallerMemberName] String message = "")
        {
            try
            {
                System.ServiceModel.OperationContext context = System.ServiceModel.OperationContext.Current;
                MessageProperties messageProperties = context.IncomingMessageProperties;
                RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

                if (LogManager._isVerbose || type.Equals(LogEntity.LogType.Message) == false)
                {
                    LogEntity logEntity = new LogEntity(message, type, duration, endpointProperty.Address);

                    TableOperation insertOperation = TableOperation.Insert(logEntity);
                    LogManager.Table.Execute(insertOperation);
                }
            }
            catch (Exception)
            {
                // Do nothing to avoid infinite loops
            }
        }
    }
}
